package client_core

import (
	coreUtil "github.com/chicken-team-outside/chicken_transmission/client_core/util"
	utils2 "github.com/chicken-team-outside/chicken_transmission/proxy_server/utils"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"os"
)

func initLocalFileApi(group *gin.RouterGroup) {
	group.GET("", getFileInfo)
	group.GET("/disk", getDiskInfo)
	group.POST("/mkdir", createFolder)
	group.POST("/del", deleteFile)
	group.POST("/rename", renameFile)
}

func getFileInfo(ctx *gin.Context) {
	path := ctx.Query("path")
	if path == "" {
		utils2.BadRequest(ctx, "path cannot be empty")
		return
	}
	folder := ctx.DefaultQuery("folder", "false")
	info, err := coreUtil.GetFileInfo(path, folder == "true")
	if err != nil {
		utils2.BadRequest(ctx, err.Error())
	} else {
		utils2.Success(ctx, "", info)
	}
}

func getDiskInfo(ctx *gin.Context) {
	info, err := coreUtil.GetDiskInfo()
	if err != nil {
		utils2.BadRequest(ctx, err.Error())
	} else {
		utils2.Success(ctx, "", info)
	}
}

func createFolder(ctx *gin.Context) {
	path := ctx.Query("path")
	if path == "" {
		utils2.BadRequest(ctx, "path cannot be empty")
		return
	}
	err := os.MkdirAll(path, os.ModePerm)
	if err != nil {
		utils2.BadRequest(ctx, err.Error())
		return
	}
	utils2.Success(ctx, "", nil)
}

type delFilesQuery struct {
	Paths []string `json:"paths"`
}

func deleteFile(ctx *gin.Context) {
	query := new(delFilesQuery)
	err := ctx.BindJSON(query)
	if err != nil {
		zap.L().Warn("failed binding query", zap.Error(err))
		utils2.BadRequest(ctx, "参数错误")
		return
	}
	for _, path := range query.Paths {
		err = os.RemoveAll(path)
		if err != nil {
			utils2.BadRequest(ctx, err.Error())
			return
		}
	}
	utils2.Success(ctx, "操作成功", nil)
}

type RenameFileQuery struct {
	OldPath string `json:"old_path" binding:"required"`
	NewPath string `json:"new_path" binding:"required"`
}

func renameFile(ctx *gin.Context) {
	query := new(RenameFileQuery)
	if err := ctx.BindJSON(query); err != nil {
		utils2.BadRequest(ctx, err.Error())
	} else if query.OldPath == "" || query.NewPath == "" {
		utils2.BadRequest(ctx, "参数不能为空!")
	} else if err = os.Rename(query.OldPath, query.NewPath); err != nil {
		utils2.BadRequest(ctx, err.Error())
	} else {
		utils2.Success(ctx, "", nil)
	}
}
